"use strict";

let fs = require('fs');
let request = require('request');
let Promise = require('bluebird');
let sharp = require('sharp');

module.exports = function (settings, storage) {
  let {paths, models: {Users}, config} = storage;
  let active1111Json = require(config.paths.json + 'active1111.json');

  return {
    /**
     * 如何下单
     */
    user_center: function (message, req, res) {
      let openid = message.FromUserName;
      let event = message.EventKey;
      console.log('http://pyl.card789.cn/user_center?openid=' + openid);
      Users.findOne({where: {openid: openid}}).then(function (user) {
        if (!user) {
          Users.create({
            openid: openid
          });
        }
      });
      return res.reply({
        type: "text",
        content: '点击链接进入个人中心\n http://pyl.card789.cn/user_center?openid=' + openid
      });
    },

    /**
     * 如何下单
     */
    help_use: function (message, req, res) {
      storage.wechatInstance.shopWebApi.uploadMedia(paths.download + 'help_use.png', 'image', function (err, result) {
        if (err) {
          console.error('\n', err.stack || err.message);
          return res.reply({
            type: "text",
            content: '获取数据失败'
          });
        }
        return res.reply({
          type: "image",
          content: {
            mediaId: result.media_id
          }
        });
      });
    },

    /**
     * 加入我们
     */
    join_us: function (message, req, res) {
      let openid = message.FromUserName;
      return Users.findOne({where: {openid: openid}}).then(function (user) {
        return Users.findOne({where: {id: (user && user.partner_id || 1)}}).then(function (partner) {
          let sendQrcode = function (qrcode_mediaid) {
            return res.reply({
              type: "image",
              content: {
                mediaId: qrcode_mediaid
              }
            });
          }
          if (partner.join_qrcode_mediaid) {
            sendQrcode(partner.join_qrcode_mediaid);
          } else {
            let qrcodeTo = storage.paths.qrcode + 'join_qrcode_' + user.id + '_' + (new Date().getTime()) + '.png';
            new Promise(function (resolve) {
              request.get(partner.join_qrcode).on('end', function () {
                resolve();
              }).pipe(fs.createWriteStream(qrcodeTo));
            }).then(function () {

              return storage.wechatInstance.shopWebApi.uploadMaterial(qrcodeTo, 'image', function (err, result) {
                console.log('上传永久图片', result);

                if (err) {
                  console.error('\n', err.stack || err.message);
                }
                storage.models.Users.update({join_qrcode_mediaid: result.media_id}, {where: {id: partner.id}});

                return sendQrcode(result.media_id);
              });
            });
          }
        });
      });
    },

    /**
     * 获取返利
     */
    get_fanli: function (message, req, res) {

    },

    /**
     * 用户海报
     */
    get_poster: function (message, req, res) {
      storage.wechatInstance.getUserByOpenid(message.FromUserName).then(function (result) {
        if (!result.success) {
          return res.reply({
            type: "text",
            content: '获取数据失败'
          });
        }
        let user = result.data;
        return storage.models.Users.findOne({
          where: {id: user.agency_id || 1},
          attributes: ['id', 'order_return_scale']
        }).then(function (agency) {
          let qrcodeTo = paths.qrcode + 'qrcode_' + user.id + '.png';
          let portraitTo = paths.qrcode + 'portrait_' + user.id + '.png';
          let replayImage;

          if (agency && agency.order_return_scale > 0) {
            replayImage = function () {
              let posterTo = paths.qrcode + 'poster_' + user.id + '_2.png';
              let replayPoster = function () {
                storage.wechatInstance.shopWebApi.uploadMedia(posterTo, 'image', function (err, result) {
                  if (err) {
                    console.error('\n', err.stack || err.message);
                    return res.reply({
                      type: "text",
                      content: '获取数据失败'
                    });
                  }
                  return res.reply({
                    type: "image",
                    content: {
                      mediaId: result.media_id
                    }
                  });
                });
              }
              if (fs.existsSync(posterTo)) {
                return replayPoster();
              } else {
                let posterBg = paths.download + 'poster_bg_2.png';
                let portrait60 = paths.qrcode + 'portrait_' + user.id + '_60_2.png';
                let qrcode215 = paths.qrcode + 'qrcode_' + user.id + '_215_2.png';

                sharp(portraitTo).resize(60, 60).toFile(portrait60, function (err, info) {
                  if (err) {
                    console.error('\n', err.stack || err.message);
                    return res.reply({
                      type: "text",
                      content: '生成图片失败'
                    });
                  }
                  sharp(qrcodeTo).resize(304, 304).overlayWith(portrait60, {
                    top: 122,
                    left: 122
                  }).toFile(qrcode215, function (err, info) {
                    if (err) {
                      console.error('\n', err.stack || err.message);
                      return res.reply({
                        type: "text",
                        content: '生成图片失败'
                      });
                    }

                    sharp(posterBg).overlayWith(qrcode215, {
                      top: 280,
                      left: 172
                    }).toFile(posterTo, function (err, info) {
                      if (err) {
                        console.error('\n', err.stack || err.message);
                        return res.reply({
                          type: "text",
                          content: '生成图片失败'
                        });
                      }

                      console.log('poster', info);
                      return replayPoster();
                    });
                  });
                });
              }
            }
          } else {
            replayImage = function () {
              let posterTo = paths.qrcode + 'poster_' + user.id + '.png';
              let replayPoster = function () {
                storage.wechatInstance.shopWebApi.uploadMedia(posterTo, 'image', function (err, result) {
                  if (err) {
                    console.error('\n', err.stack || err.message);
                    return res.reply({
                      type: "text",
                      content: '获取数据失败'
                    });
                  }
                  return res.reply({
                    type: "image",
                    content: {
                      mediaId: result.media_id
                    }
                  });
                });
              }
              if (fs.existsSync(posterTo)) {
                return replayPoster();
              } else {
                let posterBg = paths.download + 'poster_bg.png';
                let portrait60 = paths.qrcode + 'portrait_' + user.id + '_60.png';
                let qrcode215 = paths.qrcode + 'qrcode_' + user.id + '_215.png';

                sharp(portraitTo).resize(60, 60).toFile(portrait60, function (err, info) {
                  if (err) {
                    console.error('\n', err.stack || err.message);
                    return res.reply({
                      type: "text",
                      content: '生成图片失败'
                    });
                  }
                  sharp(qrcodeTo).resize(215, 215).overlayWith(portrait60, {
                    top: 77,
                    left: 77
                  }).toFile(qrcode215, function (err, info) {
                    if (err) {
                      console.error('\n', err.stack || err.message);
                      return res.reply({
                        type: "text",
                        content: '生成图片失败'
                      });
                    }

                    sharp(posterBg).overlayWith(qrcode215, {
                      top: 620,
                      left: 214
                    }).toFile(posterTo, function (err, info) {
                      if (err) {
                        console.error('\n', err.stack || err.message);
                        return res.reply({
                          type: "text",
                          content: '生成图片失败'
                        });
                      }

                      console.log('poster', info);
                      return replayPoster();
                    });
                  });
                });
              }
            }
          }

          if (fs.existsSync(qrcodeTo)) {
            return replayImage();
          }
          storage.wechatInstance.shopWebApi.createLimitQRCode(user.id, function (err, result) {
            if (err) {
              console.error('\n', err.stack || err.message);
              return res.reply({
                type: "text",
                content: '获取数据失败'
              });
            }
            let qrcodeUrl = storage.wechatInstance.shopWebApi.showQRCodeURL(result.ticket);
            let portraitUrl = user.image || 'http://a4.xcworld.cn/images.jpeg';
            return Promise.all([new Promise(function (resolve) {
              request.get(qrcodeUrl).on('end', function () {
                resolve();
              }).pipe(fs.createWriteStream(qrcodeTo));
            }), new Promise(function (resolve) {
              request.get(portraitUrl).on('end', function () {
                resolve();
              }).pipe(fs.createWriteStream(portraitTo));
            })]).then(function () {
              return replayImage();
            });
          });

        });
      });
    },

    /**
     * 其它
     */
    others: function (message, req, res) {
      let openid = message.FromUserName;
      let event = message.EventKey;
      return Users.findOne({where: {openid: openid}}).then(function (user) {
        let text = active1111Json[user.partner_id] && active1111Json[user.partner_id][event];
        if (!text) {
          text = active1111Json[1] && active1111Json[1][event];
        }
        return res.reply({
          type: "text",
          content: text ? text.text : "最高抢1111元现金红包，每天可抢三次[色]\n\n【口令】￥6Aqo0gIqwke￥\n复制这条信息，打开☞手机淘宝"
        });
      });
    },
  };
}
